package com.realbrand.net.realbrandpay.ui.activity.pickcode;

import android.content.Intent;
import android.content.SharedPreferences;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.realbrand.net.realbrandpay.APP;
import com.realbrand.net.realbrandpay.R;
import com.realbrand.net.realbrandpay.adapter.PickCodeOneAdapter;
import com.realbrand.net.realbrandpay.base.BaseActivity;
import com.realbrand.net.realbrandpay.base.FirstActivity;
import com.realbrand.net.realbrandpay.bean.BundleBean;
import com.realbrand.net.realbrandpay.bean.PickBean;
import com.realbrand.net.realbrandpay.bean.PickCodeBean;
import com.realbrand.net.realbrandpay.ui.activity.login.LoginActivity;
import com.realbrand.net.realbrandpay.ui.activity.mall.MallCarActivity;
import com.realbrand.net.realbrandpay.ui.activity.shopcar.CheckOutActivity;
import com.realbrand.net.realbrandpay.ui.activity.shopcar.ShopCarActivity;
import com.realbrand.net.realbrandpay.ui.activity.wallet.WalletActivity;
import com.realbrand.net.realbrandpay.ui.activity.wallet.set.WalletLogoutActivity;
import com.realbrand.net.realbrandpay.untils.Constant;
import com.realbrand.net.realbrandpay.untils.Static;
import com.realbrand.net.realbrandpay.zxing.app.CaptureActivity;
import com.realbrand.net.realbrandpay.zxing.util.L;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by lenovo on 2018/9/25.
 */

public class PickCodeActivity extends FirstActivity {
    @BindView(R.id.act_pickCode_toolBar)
    Toolbar actPickCodeToolBar;
    @BindView(R.id.act_pickCode_listView)
    ListView actPickCodeListView;
    @BindView(R.id.act_pickCode_tv_money)
    TextView actPickCodeTvMoney;
    @BindView(R.id.act_pickCode_bt_confirm)
    Button actPickCodeBtConfirm;
    @BindView(R.id.act_pickCode_tv_scan)
    TextView actPickCodeTvScan;
    @BindView(R.id.act_pickCode_tv_mall)
    TextView actPickCodeTvMall;
    @BindView(R.id.act_pickCode_tv_shopCar)
    TextView actPickCodeTvShopCar;
    @BindView(R.id.act_pickCode_tv_my)
    TextView actPickCodeTvMy;
    public String jsonPickCode;
    List<PickBean> pickBeanList;
    List<PickCodeBean> pickdata;

    PickCodeOneAdapter oneAdapter;
    @BindView(R.id.act_pickCode_tv)
    TextView actPickCodeTv;
    @BindView(R.id.act_pickCode_liner)
    LinearLayout actPickCodeLiner;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
        ButterKnife.bind(this);
        jsonPickCode = getIntent().getStringExtra("pickCode");
        init();
        setOnClick();

    }

    private void init() {
        actPickCodeToolBar.setTitle("");
//        actPickCodeToolBar.setNavigationIcon(R.mipmap.ic_back);
        setSupportActionBar(actPickCodeToolBar);
//        actPickCodeToolBar.setNavigationOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                finish();
//            }
//        });
        pickBeanList = new ArrayList<>();
        pickdata = new ArrayList<>();
        jsonString(jsonPickCode);
        L.d(L.TAG, pickdata.toString());
        oneAdapter = new PickCodeOneAdapter(pickdata, this);
        actPickCodeListView.setAdapter(oneAdapter);
        oneAdapter.registerDataSetObserver(observer);
        oneAdapter.notifyDataSetChanged();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.act_pickcode;
    }

    @Override
    protected void setOnClick() {
        actPickCodeBtConfirm.setOnClickListener(this);
        actPickCodeTvMall.setOnClickListener(this);
        actPickCodeTvMy.setOnClickListener(this);
        actPickCodeTvScan.setOnClickListener(this);
        actPickCodeTvShopCar.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.act_pickCode_bt_confirm://确认
                if (pickdata.size() != 0) {
                    SharedPreferences sharedPreferences = getSharedPreferences(Constant.shareName, MODE_PRIVATE);
                    SharedPreferences.Editor edit = sharedPreferences.edit();
                    edit.putString(Constant.shopCarMoney, actPickCodeTvMoney.getText().toString());
                    edit.commit();
                    BundleBean bundleBean = new BundleBean();
                    bundleBean.setList(pickBeanList);
                    if (LoginActivity.isLogin) {
                        Intent intent_count = new Intent(this, CheckOutActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putString("forWhere", "pick");
                        bundle.putSerializable("bean", bundleBean);
                        intent_count.putExtras(bundle);
                        startActivity(intent_count);
                    } else {
                        Intent intent = new Intent(this, LoginActivity.class);
                        intent.putExtra(Constant.formShopCar, "pick");
                        startActivity(intent);
                    }
                } else {
                    Static.toast(this, "请扫描包装码进行签收结算");
                }
                break;
            case R.id.act_pickCode_tv_mall://商城
                if (LoginActivity.isLogin) {
                    startActivity(new Intent(this, MallCarActivity.class));
                    finish();
                } else {
                    Intent intent1 = new Intent(this, LoginActivity.class);
                    intent1.putExtra("whereActivity", "WalletLogout");
                    startActivity(intent1);
                    finish();
                }
                break;
            case R.id.act_pickCode_tv_my://钱包
                if (LoginActivity.isLogin) {
                    startActivity(new Intent(this, WalletActivity.class));
                    finish();
                } else {
                    startActivity(new Intent(this, WalletLogoutActivity.class));
                    finish();
                }
                break;
            case R.id.act_pickCode_tv_shopCar://购物车
                startActivity(new Intent(this, ShopCarActivity.class));
                finish();
                break;
            case R.id.act_pickCode_tv_scan://扫码
                Intent scanIntent = new Intent(this, CaptureActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString(Static.BundleKey, "pickCode");
                scanIntent.putExtras(bundle);
                startActivityForResult(scanIntent, 01);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 01:
                    String result = data.getStringExtra("pickCode");
                    pickBeanList.clear();
                    pickdata.clear();
                    jsonString(result);
                    oneAdapter.notifyDataSetChanged();
                    break;
            }
        }
    }

    /**
     * 解析数据
     *
     * @param reslut
     */
    public void jsonString(String reslut) {
        try {
            JSONObject object = new JSONObject(reslut);
            JSONArray store = object.getJSONArray("EnterpriseName");
            JSONArray userAddress = object.getJSONArray("RegisterAddress");
            JSONArray commodityName = object.getJSONArray("CommodityName");
            JSONArray commodityCode = object.getJSONArray("CommodityCode");
            JSONArray supplyMoney = object.getJSONArray("SupplyMoney");
            JSONArray filePath = object.getJSONArray("FilePath");
            JSONArray scanState = object.getJSONArray("ScanState");
            String userAccount = object.getString("UserAccount");
            JSONArray bankName = object.getJSONArray("BankName");
            for (int i = 0; i < bankName.length(); i++) {
                if (bankName.getString(i).equals("微信")) {
                    APP.supportWX = true;
                } else if (bankName.getString(i).equals("支付宝")) {
                    APP.supportAlipay = true;
                } else {
                    APP.supportAlipay = false;
                    APP.supportWX = false;
                }
            }
            for (int i = 0; i < commodityName.length(); i++) {
                PickBean pickBean = new PickBean();
                pickBean.setAddress(userAddress.getString(i));
                pickBean.setStoreName(store.getString(i));
                pickBean.setName(commodityName.getString(i));
                pickBean.setImgUrl(filePath.getString(i));
                pickBean.setPrice(supplyMoney.getString(i));
                pickBean.setScan(commodityCode.getString(i));
                pickBean.setScanState(scanState.getString(i));
                pickBean.setUserAccount(userAccount);
                pickBeanList.add(pickBean);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        for (int n = 0; n < pickBeanList.size(); n++) {
            List<String> scanList = new ArrayList<>();
            PickCodeBean bean = new PickCodeBean();
            bean.setPrice(pickBeanList.get(n).getPrice());
            bean.setImgUrl(pickBeanList.get(n).getImgUrl());
            bean.setGoodsName(pickBeanList.get(n).getName());
            bean.setStoreAddress(pickBeanList.get(n).getAddress());
            bean.setStoreName(pickBeanList.get(n).getStoreName());
            bean.setSum(1);
            scanList.add(pickBeanList.get(n).getScan());
            bean.setGoodsScanList(scanList);
            if (pickdata.size() == 0) {
                pickdata.add(bean);
            } else {
                int t = -1;
                for (int j = 0; j < pickdata.size(); j++) {
                    if (pickBeanList.get(n).getName().equals(pickdata.get(j).getGoodsName())) {
                        pickdata.get(j).setSum(pickdata.get(j).getSum() + 1);
                        pickdata.get(j).getGoodsScanList().add(pickBeanList.get(n).getScan());
                        t = j;
                    }
                }
                if (t < 0) {
                    pickdata.add(bean);
                }
            }
        }
    }

    /**
     * 计算总价格
     */
    private DataSetObserver observer = new DataSetObserver() {
        @Override
        public void onChanged() {
            super.onChanged();
            double money = 0.00;
//            for (int i = 0; i < pickdata.size(); i++) {
//                double v = Double.parseDouble(pickdata.get(i).getPrice()) * pickdata.get(i).getSum();
//                money += v;
//            }
            for (int j = 0; j < pickBeanList.size(); j++) {
                if (pickBeanList.get(j).getScanState().equals("1")) {
                    money += Double.parseDouble(pickBeanList.get(j).getPrice());
                }
            }
            if (money == 0.00) {
                actPickCodeLiner.setVisibility(View.GONE);
                actPickCodeTv.setVisibility(View.VISIBLE);
            } else {
                actPickCodeLiner.setVisibility(View.VISIBLE);
                actPickCodeTvMoney.setText(new DecimalFormat("0.00").format(money));
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        oneAdapter.unregisterDataSetObserver(observer);
    }
}
